#include <QtTest>

// add necessary includes here
#include "CDatabaseManager.h"
#include "CTableHistory.h"
#include <QThread>
#include <QTimer>

class MultiThreading : public QObject
{
    Q_OBJECT

public:
    MultiThreading();
    ~MultiThreading();

private slots:
    void initTestCase();
    void cleanupTestCase();
    void testMultiThreadWrite();
    void testMultiThreadRead();
};

MultiThreading::MultiThreading()
{

}

MultiThreading::~MultiThreading()
{

}

void MultiThreading::initTestCase()
{
    CDatabaseManager::instance()->init("./testMutiThread.db");
    CDatabaseManager::instance()->setSynMode(CDatabaseManager::Normal);
}

void MultiThreading::cleanupTestCase()
{

}

void MultiThreading::testMultiThreadWrite()
{
    QBENCHMARK
    {
        auto addRow = []{
            QString varId = QUuid::createUuid().toString();

            RowHistory row;
            row.id = varId;
            row.date = 2022;
            row.info = "[INFO]";
            row.message = "multi thread add row";
            row.dateTime = QDateTime::currentDateTime();
            //        qDebug()<<"addRow:"<<row;
            QVERIFY(CTableHistory::getInstance()->addRow(row));
        };
        qDebug()<<"线程开始";
        std::thread thread1([&]()
        {
            for(int i = 0; i < 100; i++){
                addRow();
                //            qDebug()<<"Thread id:"<<QThread::currentThreadId();
            }
        });
        std::thread thread2([&]()
        {
            for(int i = 0; i < 100; i++){
                addRow();
                //            qDebug()<<"Thread id:"<<QThread::currentThreadId();
            }
        });

        thread1.join();
        thread2.join();
        qDebug()<<"线程结束";
    }
}

void MultiThreading::testMultiThreadRead()
{
    QBENCHMARK
    {
        int nCnt = 0;

        //1.添加一行
        QString varId = QUuid::createUuid().toString();

        RowHistory row;
        row.id = varId;
        row.date = 2022;
        row.info = "[INFO]";
        row.message = "multi thread query row";
        row.dateTime = QDateTime::currentDateTime();
        QVERIFY(CTableHistory::getInstance()->addRow(row));

        //反复读写
        qDebug()<<"线程开始";
        std::thread thread1([&]()
        {
            int i = 10000;
            while (--i > 0) {
                RowHistory row;
                QVERIFY(CTableHistory::getInstance()->queryRow(varId,row));
                nCnt++;
            };
        });
        std::thread thread2([&]()
        {
            int i = 10000;
            while (--i > 0) {
                RowHistory row;
                QVERIFY(CTableHistory::getInstance()->queryRow(varId,row));
                nCnt++;
            };
        });

        thread1.join();
        thread2.join();
        qDebug()<<QString("线程结束,双线程 读次数:%1  ").arg(nCnt);
    }
}

QTEST_APPLESS_MAIN(MultiThreading)

#include "tst_multithreading.moc"
